package com.sjf.JavaNIO.buffer;

import org.junit.Test;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

/**
 * Buffer的一些基本操作，比如读和写操作
 *
 * @author <huangtang>
 * @since 2022/4/14 10:27
 **/
public class BufferDemo1 {

    //Buffer读的操作
    @Test
    public void buffer01 () throws Exception {
        //创建一个FileChannel
        RandomAccessFile aFile = new RandomAccessFile ("D:\\atguigu\\01.txt" , "rw");
        FileChannel channel = aFile.getChannel ();
        //创建一个Buffer
        ByteBuffer buffer = ByteBuffer.allocate (128);
        //从channel中读取数据到buffer中
        int readLength = channel.read (buffer);//写入的字节数

        while (readLength != -1) {
            //将position指针指向开头重新获取buffer的数据
            buffer.flip ();
            while (buffer.hasRemaining ()) {
                //buffer的position指针还未指向limit(limit通常用来指向buffer的末尾)
                System.out.print ((char) buffer.get ()); //get()方法获取position指向位置的字符
            }
            buffer.clear ();
            readLength = channel.read (buffer);
        }
        aFile.close ();
    }

    /**
     * 往buffer里面写入数据和取出数据
     *
     * @throws Exception
     */
    @Test
    public void buffer02 () throws Exception {
        //创建FileChannel,即文件IO通道
        RandomAccessFile aFile = new RandomAccessFile ("D:\\atguigu\\02.txt" , "rw");
        FileChannel channel = aFile.getChannel ();
        //创建一个IntBuffer
        IntBuffer buffer = IntBuffer.allocate (8);
        //往buffer里面放数据
        for ( int i = 0 ; i < buffer.capacity () ; i++ ) {
            buffer.put (2 * (i + 1));
        }

        //重置position指针
        buffer.flip ();

        //获取buffer数据
        while (buffer.hasRemaining ()) {
            System.out.println (buffer.get ());
        }

    }
}
